package com.loong.user.handler;

import com.loong.common.nacos.DynamicKey;
import com.loong.common.rest.Result;
import com.loong.common.wechat.auth.AuthUtils;
import com.loong.common.wechat.model.result.AccessTokenResult;
import com.loong.common.wechat.model.result.UserInfoWeChatResult;
import com.loong.global.constant.DynamicConfigKey;
import com.loong.global.dynamic.wechat.WeChatConfig;
import com.loong.user.business.WeChatLoginBusiness;
import com.loong.user.common.forehead.param.WeChatLoginRequestParam;
import com.loong.user.model.UserThird;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;

/**
 * 微信控制服务
 */
@Component
public class WeChatLoginHandler {

    @Resource
    private WeChatLoginBusiness weChatLoginBusiness;
    @Resource
    private AuthUtils authUtils;
    @Resource
    private DynamicKey dynamicKey;

    /**
     * 微信授权登录
     * @param requestParam
     * @return
     */
    public Result login(WeChatLoginRequestParam requestParam){
        //若用户禁止授权，则重定向后不会带上code参数，仅会带上state参数
        //redirect_uri?state=STATE
        if(ObjectUtils.isNotEmpty(requestParam)){
            if(ObjectUtils.isNotEmpty(requestParam.getCode())){
                //检查code是否存在 不存在就是未经用户授权
            }
        }

        WeChatConfig dynamicValue = dynamicKey.getDynamicValue(DynamicConfigKey.WECHAT.WECHAT_WX_KEY, WeChatConfig.class);
        //小程序相关信息
        String appId=dynamicValue.getAppId();
        String secret = dynamicValue.getSecret();
        //获取access_token and openId
        AccessTokenResult accessTokenResult = authUtils.accessToken(appId, secret, requestParam.getCode());

        UserInfoWeChatResult userInfo = authUtils.getUserInfo(accessTokenResult.getAccessToken(), accessTokenResult.getOpenId());
        UserThird user = weChatLoginBusiness.findBy("identifier", userInfo.getOpenId());


        //检查用户是否存在
        if(ObjectUtils.isNotEmpty(user)){
            //存在

        }else {
            //不存在就入库
            //UserThird.builder()
        }
        //user-->redis


        return Result.success().build();
    }
}
